package net.example.lesson6.concurrent;

import java.util.Map;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierSum {
    //子线程结果存放的缓存
    private static ConcurrentHashMap<String,Integer> resultMap = new ConcurrentHashMap<>();
    private static CyclicBarrier c = new CyclicBarrier(11,new SumThread());

    //所有子线程达到屏障后，会执行这个Runnable的任务
    private static class SumThread implements Runnable{
        @Override
        public void run() {
            int result =0;
            for(Map.Entry<String,Integer> workResult:resultMap.entrySet()){
                result = result+workResult.getValue();
            }
            System.out.println("所有累加结果为sum="+result);
        }
    }

    //工作线程，也就是子线程
    private static class WorkThread implements Runnable{
        private final int begin;
        private final int end;
        private final int num;
        public WorkThread(int begin, int end, int num) {
            this.begin = begin;
            this.end = end;
            this.num = num;
        }
        @Override
        public void run() {
            try {
                Thread.sleep(1000 * num);
                int sum = 0;
                for (int i = begin; i <= end; i++) {
                    sum += i;
                }
                resultMap.put(num + "", sum);
                System.out.println(String.format("线程%d计算完从%d到%d累加的结果为%d", num, begin, end, sum));
                c.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {

        for(int i = 0;i < 11; i++){
            Thread thread = new Thread(new WorkThread(i * 10, (i + 1) * 10 - 1, i));
            thread.start();
        }
    }
}
